﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;

namespace TSTech_WebService
{
    public class DBOperation : IDisposable
    {
        //将下面的引号之间的内容换成上面记录下的属性中的连接字符串
        public static string _xml_SysSetting_CompanyName = "武汉铁路局大功率机车检修段";
        private String ConServerStr = @"Data Source=.;Initial Catalog=TS_DGL_Repair_Data;password=Windows2008;Pooling=false;persist security info=True;user id=sa;workstation id=SERVER;packet size=4096";

        #region//--基础函数--//
        //默认构造函数
        public DBOperation()
        {
        }

        //关闭/销毁函数，相当于Close()
        public void Dispose()
        {
        }
        public static string CutLast0(string str)
        {
            string _str = str;
            if (_str.IndexOf('.') > -1)
            {
                while (_str.LastIndexOf("0") == _str.Length - 1)
                {
                    _str = _str.Substring(0, _str.Length - 1);
                }
                if (_str.LastIndexOf(".") == _str.Length - 1)
                {
                    _str = _str.Substring(0, _str.Length - 1);
                }
            }
            return _str;
        }
        public string Create_Worker_Code(string strTrainTypeName, string strTrainNumber)
        {
            string strReturn = strTrainTypeName + strTrainNumber.PadLeft(4, '0') + DateTime.Now.Year.ToString().PadLeft(4, '0') + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0') + DateTime.Now.Hour.ToString().PadLeft(2, '0') + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0');
            return strReturn;
        }
        public string MySqlComGetID(string strSql)
        {
            SqlConnection MyClassConn = new SqlConnection(ConServerStr);
            strSql = strSql + ";select @@IDENTITY As 'Identity'";
            SqlCommand MyClassComm = new SqlCommand(strSql, MyClassConn);
            MyClassConn.Open();
            string Index = (MyClassComm.ExecuteScalar()).ToString().Trim();
            MyClassConn.Close();
            MyClassConn.Dispose();
            return Index;
        }
        public string GetSQlFieldValue(string strSql, string Field)
        {
            string str = "";
            SqlConnection conn = new SqlConnection(ConServerStr);
            conn.Open();
            SqlCommand comm = new SqlCommand(strSql, conn);
            SqlDataReader read = comm.ExecuteReader();
            if (read.HasRows)
            {
                read.Read();
                str = read[Field].ToString().Trim();
            }
            else
            {
                str = null;
            }
            conn.Close();
            return str;
        }
        public string GetSQlFieldValue(string strSql, string Field, string sHandle)
        {
            string str = "";
            SqlConnection conn = new SqlConnection(ConServerStr);
            conn.Open();
            SqlCommand comm = new SqlCommand(strSql, conn);
            SqlDataReader read = comm.ExecuteReader();
            if (read.HasRows)
            {
                read.Read();
                str = read[Field].ToString().Trim();
            }
            else
            {
                str = null;
            }
            conn.Close();
            return str;
        }
        public void MySqlCom(string strSql)
        {
            SqlConnection MyClassConn = new SqlConnection(ConServerStr);
            SqlCommand MyClassComm = new SqlCommand(strSql, MyClassConn);
            MyClassConn.Open();
            MyClassComm.ExecuteNonQuery();
            MyClassConn.Close();
            MyClassConn.Dispose();
        }
        #endregion

    }
    #region <<--加密算法 DESEncrypt
    public class DESEncrypt
    {
        public DESEncrypt()
        { }
        #region =========加密===========
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public string Encrypt(string Text)
        {
            return Encrypt(Text, DBOperation._xml_SysSetting_CompanyName);
        }

        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Encrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray;
            inputByteArray = Encoding.Default.GetBytes(Text);
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }
        #endregion
        #region =======解密==================
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public string Decrypt(string Text)
        {
            return Decrypt(Text, DBOperation._xml_SysSetting_CompanyName);
        }
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="sKey"></param>
        /// <returns></returns>
        public static string Decrypt(string Text, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            int len;
            len = Text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }
        #endregion
        #region
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">要加密的字符串</param>
        /// <returns></returns>
        public string md5(string str)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
        }
        #endregion
    }
    #endregion
}